<template>
  <div class="page-wrapper">
    <div class="content">
      <el-dialog
          title="发布作业"
          v-model="PublicDialogVisible"
          width="40%"
          :append-to-body="true"
          align-center
          >
        <el-form>
          <el-form-item label="发布时间：">
            <el-config-provider :locale="locale">
              <el-date-picker value-format="YYYY-MM-DD" format="YYYY-MM-DD" v-model="StartDate" type="date" placeholder="选择日期" ></el-date-picker>
              <el-time-picker value-format="HH:mm:ss" v-model="StartTime" style="padding-left: 50px" :picker-options="{selectableRange: '00:00:00 - 00:00:00'}" placeholder="时间"></el-time-picker>
            </el-config-provider>
          </el-form-item>

          <el-form-item label="结束时间：">
            <el-config-provider :locale="locale">
              <el-date-picker value-format="YYYY-MM-DD" format="YYYY-MM-DD" v-model="EndDate" type="date" placeholder="选择日期" ></el-date-picker>
              <el-time-picker value-format="HH:mm:ss" v-model="EndTime" :picker-options="{selectableRange: '00:00:00 - 00:00:00'}" style="padding-left: 50px" placeholder="时间"></el-time-picker>

            </el-config-provider>
          </el-form-item>

          <el-form-item label="发放班级">
            <el-checkbox-group v-model="clazz">
              <el-checkbox v-for="clazz in clazzList" :label="clazz" :key="clazz">{{clazz}}</el-checkbox>

            </el-checkbox-group>
          </el-form-item>

        </el-form>
        <template #footer>
          <span slot="footer" class="dialog-footer">
            <el-button @click="PublicDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="SubmitPublish()">确 定</el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog
          title="创建作业"
          v-model="CreateDialogVisible"
          width="40%"
          :append-to-body="true"
          align-center
      >
        <el-input placeholder="请输入作业名" v-model="taskName"></el-input>
        <el-upload
            class="upload-demo"
            action="quest/import"
            :on-remove="handleRemove"
            :before-upload="handleBeforeUpload"
            accept=".xls,.xlsx"
            :http-request="submitUpload"
            :file-list="fileList"
            style="margin-top: 20px;margin-bottom: 20px">
          <el-button style="margin-left: 10px;" type="success" plain>导入新作业</el-button>
          <div slot="tip" class="el-upload__tip">只能上传excel文件，且不超过3Mb</div>
        </el-upload>

        <template #footer>
          <span slot="footer" class="dialog-footer">
            <el-button @click="CreateDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="CreateDialogVisible = false">确 定</el-button>
          </span>
        </template>
      </el-dialog>

      <el-row>
        <el-col :span="4"><el-button type="primary" plain style="margin-bottom: 20px;margin-top: 20px;margin-left: 60px" @click="getModel()">下载导入模板</el-button></el-col>
        <el-col :span="8">
          <el-button type="primary" plain style="margin-bottom: 20px;margin-top: 20px;margin-left: 60px" @click="CreateDialogVisible = true">导入作业</el-button>
        </el-col>
        <el-col :span="4"><el-button type="primary" plain style="margin-bottom: 20px;margin-top: 20px;margin-left: 500px" @click="handleCreate">手动创建</el-button></el-col>
      </el-row>
      <el-table
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName"
          :header-cell-style="{'text-align':'center'}"
          :cell-style="{'text-align':'center'}"
          border>
        <el-table-column prop="num" label="作业号"></el-table-column>
        <el-table-column prop="name" label="作业名"></el-table-column>
        <el-table-column prop="status" label="作业状态"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
          <el-dropdown>
          <el-button type="success">
            作业操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="PublicHW(scope.row)">发布作业</el-dropdown-item>
              <el-dropdown-item @click="DeleteHw(scope.row)">删除作业</el-dropdown-item>
              <el-dropdown-item @click="changeQuest(scope.row)">修改作业</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="padding-left: 120px"
          background
          layout="prev, pager, next"
          :total="this.total"
          :page-size="this.page.pageSize">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'
import axios from 'axios'
import zhCn from "element-plus/lib/locale/lang/zh-cn";
export default {
  name: "PublishHomework",
  setup() {
    let PublicDialogVisible = ref(false)
    let CreateDialogVisible = ref(false)
    function handleClose(done) {
      this.$confirm('确认关闭？')
          .then((_) => {
            done()
          })
          .catch((_) => {})
    }
    return {
      handleClose,
      PublicDialogVisible,
      CreateDialogVisible,
      locale: zhCn,
    }
  },
  components:{
    ArrowDown
  },
  created() {
    this.load();
  },
  methods: {
    SubmitPublish(){

      this.PublicDialogVisible = false
      let startTime = this.StartDate.concat(" ",this.StartTime);
      let endTime = this.EndDate.concat(" ",this.EndTime);
      console.log(startTime);
      console.log(endTime);
      console.log(this.clazz)
      var obj = {
        startTime:startTime,
        endTime:endTime,
        classes:this.clazz,
        taskNum:this.taskNum
      }
      axios.post('/api/task/PublishTask',obj).then(res=>{
        console.log(res);
      }).catch(error=>{
        console.log(error);
      })
    },
    changeQuest(scope){
      this.$router.push({name:'ChangeQuests',params:{type:parseInt('3'),TaskNum:scope.num}});
    },
    load(){

      axios.post('/api/task/GetUnpublishedTask',this.page).then(res=>{
        console.log(res);
        this.total =  res.data.data.total
        this.tableData = res.data.data.list
        for (let i = 0; i < this.tableData.length; i++) {
          this.tableData[i].status = '未发放'
        }

      }).catch(error=>{
        console.log(error);
      })

      var userJsonStr = sessionStorage.getItem('User');
      let userEntity = JSON.parse(userJsonStr);
      axios.get('/api/class/GetClazzByTeacherno',{params:{teacherNo:userEntity.num}}).then(res=>{
        this.clazzList = res.data.split(";");
        console.log(this.clazzList);
      })

    },
    PublicHW(scope){
      this.PublicDialogVisible = true
      this.taskNum = scope.num
    }
    ,
    getModel(){
      window.open('/api/quest/Export')
    },
    submitUpload() {
      let formData = new FormData();
      console.log(this.fileList[0]);
      formData.append("file", this.fileList[0]);
      formData.append("taskName",this.taskName)
      formData.append("type","0")
      console.log(formData);
      axios.post(
          '/api/quest/import',
          formData,
          {headers:{'Content-Type':'multipart/form-data'}}
          ).then(res=>{
        this.$message.success("上传成功")
      }).catch( e =>{
        console.log(e);
        this.$message.warning("上传失败，请检查")
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 文件上传之前
    handleBeforeUpload(file){
      if(this.taskName===''){
        this.$message.warning("请先输入任务名");
        return false;
      }
      if(this.fileList.length > 1){
        this.$message.warning("只能上传一个文件");
        return false;
      }
      let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
      if(fileType == 'xls' || fileType == 'xlsx'){
        this.fileList.push(file);
      }else{
        this.$message.warning("只能上传.xls和.xlsx格式的文件");
        return false;
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },
    handleCreate(){
      this.$router.push('/Teacher/CreateHomework')
    },
    DeleteHw(scope){
      console.log(scope);
      this.$confirm('此操作将永久删除该作业, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        axios.get("/api/task/DeleteTask",{params:{taskNum:scope.num}}).then(res=>{
          console.log(res);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.load();
        }).catch(error=>{
          this.$message({
            type: 'warning',
            message:'删除失败'
          })
        })



      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },

  data() {
    return {
      tableData: [],
      fileList: [],
      StartTime:undefined,
      StartDate:undefined,
      EndTime:undefined,
      EndDate:undefined,
      clazz:[],
      taskName:'',
      page:{pageNum:1,pageSize:10,query:0},
      total:undefined,
      clazzList:[],
      taskNum:undefined
    }
  }
}
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.el-dropdown {
  vertical-align: top;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.el-table-column{
  width: 13%;
}

.el-pagination{
  text-align:center;
  padding-top:30px;
  margin-left: 40%;
}
</style>